const tencentcloud = require("tencentcloud-sdk-nodejs");
const SMSClient = tencentcloud.sms.v20210111.Client;
import { secretId,secretKey } from "src/setting";
const clientConfig = {
    credential: {
        secretId: secretId,
        secretKey: secretKey,
    },
    region: "ap-beijing",
    profile: {
        httpProfile: {
        endpoint: "sms.tencentcloudapi.com",
        },
    },
};
import { RedisInstance } from './redis';
import { Redis } from "ioredis";

class SMSTemp{
    constructor(){

    }
    redis = undefined
    redisKey = 'sms:logincode:'
        
    getRedis(){
        if(!this.redis){
            const redis = RedisInstance.initRedis();
            this.redis = redis
        }
        return this.redis
    }

    send(phone){
        const client = new SMSClient(clientConfig);
        //生成验证码
        let validCode = Math.floor((Math.random() * 999999)).toString()
        let expire = 60
        const params = {
            "PhoneNumberSet": [phone],
            "SmsSdkAppId": '1400796367',
            "TemplateId": '1912227',
            "SignName": '椰子泛娱科技',
            "TemplateParamSet":[
                validCode.toString(),
                (expire / 60).toString()
            ],
        };
        return new Promise((resolve,reject) => {
            client.SendSms(params).then(
                (data) => {
                    if(data.SendStatusSet[0].Code === 'Ok' && data.SendStatusSet[0].Fee === 1){
                        const redis:Redis = this.getRedis()
                        let key = this.redisKey + phone
                        redis.set(key,validCode)
                        redis.expire(key, expire)
                        resolve(true)
                    }else{
                        reject(data.SendStatusSet[0].Message)
                    }
                },
                (err) => {
                    reject(err)
                }
            );
        })
    }

    async validCode(phone, validCode){
        const redis:Redis = this.getRedis()
        let code = await redis.get(this.redisKey + phone)
        console.log(code, validCode,' validCode', phone)
        if(code === validCode){
            return true
        }else{
            return false
        }
    }
}
let SMS = new SMSTemp()
export default SMS